//
//  DataManager.m
//  Gorilla
//
//  Created by 张 霄鹤 on 10-2-4.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "DataManager.h"

#define SUINDEX @"su"

static DataManager *managerInstance = nil;

@implementation DataManager

@synthesize fetchedResultsController;
@synthesize managedObjectContext;
@synthesize token;
@synthesize update;
@synthesize proxyAddress;

+ (DataManager *)sharedManager{
	if(managerInstance == nil){
		managerInstance = [[DataManager alloc] init];
	}
	return managerInstance;
}

- (id)init{
	if(self = [super init]){
		accounts = [[NSMutableArray alloc] init];
	}
	return self;
}

/**
 * 保存对象到文件
 */
+ (BOOL)saveObjectToFile:(id)items withName:(NSString *)path{
	NSString *resourcePath =  [DataManager applicationDocumentsDirectory];
	NSString *plistPath = [resourcePath stringByAppendingPathComponent:path];
	BOOL bOk = [NSKeyedArchiver archiveRootObject:items toFile:plistPath];
	return bOk;
}

/**
 * 加载对象
 */
+ (id)loadObjectFromFile:(NSString *)path{
	NSString *resourcePath =  [DataManager applicationDocumentsDirectory];
	// 此处字符串 采用 快捷方式创建，不需要释放
	NSString *plistPath = [resourcePath stringByAppendingPathComponent:path];
	id iobj = [NSKeyedUnarchiver unarchiveObjectWithFile:plistPath];
	return iobj;
}

+ (BOOL)saveBinaryToFile:(NSData *)data withName:(NSString *)path{
	BOOL bret = NO;
	if(data && path){
		NSString *resourcePath =  [DataManager applicationDocumentsDirectory];
		NSString *target = [resourcePath stringByAppendingPathComponent:path];
		bret = [data writeToFile:target atomically:NO];
	}
	return bret;
}

+ (NSData *)loadBinaryFromFile:(NSString *)path{
	NSData *ret = nil;
	if(path){
		NSString *resourcePath =  [DataManager applicationDocumentsDirectory];
		NSString *target = [resourcePath stringByAppendingPathComponent:path];
		ret = [NSData dataWithContentsOfFile:target];
	}
	return ret;
}

#pragma mark -
#pragma mark Sync Data

- (void)updateData:(NSString *)address toDataFile:(NSString *)dfile{

}

- (NSFetchedResultsController *)fetchedResultsControllerForName:(NSString *)entityName withSortKey:(NSString *)sortKey{
   
    /*
	 Set up the fetched results controller.
	 */
	// Create the fetch request for the entity.
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
	// Edit the entity name as appropriate.
	NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
	[fetchRequest setEntity:entity];
	
	// Set the batch size to a suitable number.
	[fetchRequest setFetchBatchSize:20];
	
	// Edit the sort key as appropriate.
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:NO];
	NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
	
	[fetchRequest setSortDescriptors:sortDescriptors];
	
	// Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	[fetchRequest release];
	[sortDescriptor release];
	[sortDescriptors release];
	
	return [aFetchedResultsController autorelease];
}

#pragma mark -
#pragma mark AccountManage

- (void)addAccount:(Account *)acc{
	if(acc){
		//NSString *ai = [[NSString alloc] initWithFormat:@"%@_:_%@",acc.name,acc.pass];
		//[accounts addObject:ai];
		//[ai release];
		[accounts addObject:acc];
	}
}

- (Account *)getAccount:(NSInteger)index{
	Account *ret = nil;
	NSInteger len = [accounts count];
	if(index > -1 && index < len){
		//NSString *ai = (NSString *)[accounts objectAtIndex:index];
//		NSRange range = [ai rangeOfString:@"_:_"];
//		if(range.location != NSNotFound){
//			ret = [[[Account alloc] init] autorelease];
//			ret.name = [ai substringToIndex:range.location];
//			ret.pass = [ai substringFromIndex:(range.location + range.length)];
//		}
		ret = [accounts objectAtIndex:index];
	}
	return ret;
}

- (BOOL)deleteAccount:(NSInteger)index{
	BOOL bret = NO;
	NSInteger len = [accounts count];
	if(index > -1 && index < len){
		[accounts removeObjectAtIndex:index];
	}
	return bret;
}

- (NSInteger)numberOfAccounts{
	return [accounts count];
}

- (BOOL)loadAccounts{
	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
	id accs = [ud objectForKey:@"tu"];
	BOOL bok = NO;
	if(accs){
		if([accs isKindOfClass:[NSArray class]]){
			NSArray *arr = (NSArray *)accs;
			NSInteger count = [arr count];
			if(count > 0){
				//[accounts setArray:arr];
				Account *acc;
				for (int i = 0; i < count; i+=2) {
					acc = [[Account alloc] init];
					acc.name = (NSString *)[arr objectAtIndex:i];
					acc.pass = (NSString *)[arr objectAtIndex:(i+1)];
					[accounts addObject:acc];
					[acc release];
				}
				bok = YES;
			}
		}
	}
	return bok;
	
}

- (void)saveAccounts{
	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
	//[ud setObject:accounts forKey:@"tu"];
	NSMutableArray *accs = [[NSMutableArray alloc] init];
	
	NSInteger count = [accounts count];
	Account *acc;
	for (int i = 0; i < count; i++) {
		acc = [accounts objectAtIndex:i];
		[accs addObject:acc.name];
		[accs addObject:acc.pass];
	}
	
	[ud setObject:accs forKey:@"tu"];
	[accs release];
	BOOL bok = [ud synchronize];
	if(bok){
		NSLog(@"save OK");
	}else{
		NSLog(@"save Error");
	}
}

#pragma mark -
#pragma mark shortenURLServicesLoad

- (NSArray *)getShortenURLServices{
	if(shortenURLServices == nil){
		NSBundle *mainBundle = [NSBundle mainBundle];
		NSString *supath = [mainBundle pathForResource:@"su" ofType:@"plist"];
		NSData *dt = [[NSData alloc] initWithContentsOfFile:supath];
		NSString *err = nil;
		if(dt){
			NSPropertyListFormat format = NSPropertyListBinaryFormat_v1_0;
			id obj = [NSPropertyListSerialization propertyListFromData:dt mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&err];
			if(err){
				[err release];
			}
			if(obj){
				shortenURLServices = [obj retain];
			}
		}
		[dt release];
	}
	return shortenURLServices;
}

- (NSString *)getShortenURLSettingName{
	NSInteger index = [self getShortenURLSettingIndex];
	NSArray *arr = [self getShortenURLServices];
	NSString *ret = @"sto";
	if(arr){
		NSDictionary *dt = [arr objectAtIndex:index];
		ret = [dt objectForKey:@"sv"];
	}
	return ret;	
}


- (NSInteger)getShortenURLSettingIndex{
	NSUserDefaults *usrDefaults = [NSUserDefaults standardUserDefaults];
	NSInteger ret = [usrDefaults integerForKey:SUINDEX];
	if(ret < 0){
		ret = 0;
	}
	
	return ret;
}

- (void)setShortenURLSettingIndex:(NSInteger)index{
		NSUserDefaults *usrDefaults = [NSUserDefaults standardUserDefaults];
		[usrDefaults setInteger:index forKey:SUINDEX];
}


#pragma mark -
#pragma mark AppDocumentPath
/**
 Returns the path to the application's documents directory.
 */
+ (NSString *)applicationDocumentsDirectory {
	// TODO 检查是否包含了 /
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}
#pragma mark -

- (void)dealloc{
	[accounts release];
	[fetchedResultsController release];
	[managedObjectContext release];
	[token release];
	[proxyAddress release];
	[shortenURLServices release];
	[super dealloc];
}

@end
